package com.library.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.library.Mapper.LendMapper;
import com.library.Mapper.UserMapper;
import com.library.commen.context.BaseContext;
import com.library.pojo.Lend;
import com.library.pojo.PageResult;
import com.library.pojo.User;
import com.library.service.LendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
public class LendServiceImpl implements LendService {
    @Autowired
    private LendMapper lendMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 管理端查询借书记录
     * @param page
     * @param pageSize
     * @param bookName
     * @param begin
     * @param end
     * @return
     */
    public PageResult pageQuery(Integer page, Integer pageSize,
                                String bookName, LocalDate begin
            , LocalDate end,Integer status) {
        PageHelper.startPage(page,pageSize);
        Page<Lend> p = lendMapper.page(bookName,begin,end,status);
        return new PageResult(p.getTotal(),p.getResult());
    }

    /**
     * 用户端借书
     * @param lend
     */
    @Override
    public void lend(Lend lend) {
        lend.setCreateTime(LocalDate.now());
        lend.setEndTime(LocalDate.now().plusDays(30));
        lend.setStatus(0);
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        String userName = user.getUserName();
        lend.setUserId(userId);
        lend.setUserName(userName);
        lendMapper.insert(lend);
    }

    /**
     * 用户查询自己的借书记录
     * @param page
     * @param pageSize
     * @param bookName
     * @param begin
     * @param end
     * @return
     */
    @Override
    public PageResult userPageQuery(Integer page, Integer pageSize,
                                    String bookName, LocalDate begin,
                                    LocalDate end) {
        Long userId = BaseContext.getCurrentId();
        PageHelper.startPage(page,pageSize);
        Page<Lend> p = lendMapper.pageForUser(bookName,begin,end,userId);
        return new PageResult(p.getTotal(),p.getResult());
    }

    /**
     * 修改是否归还
     * @param status
     * @param id
     */
    @Override
    public void isStatus(Integer status, Long id) {
        lendMapper.isStatus(status,id);
    }
}
